JBoss Community Archive (Read Only)

Arquillian Old

Testing CDI beans

Here's an example of an JUnit Arquillian test that validates the GreetingManager EJB session bean again, but this time it's injected into the test class using the @Inject annotation. You could also make GreenManager a basic managed bean and inject it with the same annotation. The test also verifies that the CDI BeanManager instance is available and gets injected. Notice that to inject beans with CDI, you have to add a beans.xml file to the test archive.

import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import org.jboss.arquillian.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.acme.ejb.GreetingManager;
import com.acme.ejb.GreetingManagerBean;

@RunWith(Arquillian.class)
public class InjectionTestCase
{
   @Deployment
   public static JavaArchive createTestArchive() {
      return ShrinkWrap.create(JavaArchive.class, "test.jar")
         .addClasses(GreetingManager.class, GreetingManagerBean.class)
         .addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
   }

   @Inject GreetingManager greetingManager;

   @Inject BeanManager beanManager;

   @Test
   public void shouldBeAbleToInjectCDI() throws Exception {
      String userName = "Earthlings";
      Assert.assertNotNull("Should have the injected the CDI bean manager", beanManager);
      Assert.assertEquals("Hello " + userName, greetingManager.greet(userName));
   }
}
JBoss.org Content Archive (Read Only), exported from JBoss Community Documentation Editor at 2020-03-10 12:18:46 UTC, last content change 2011-04-16 15:27:03 UTC.